package com.wf.course.service.impl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mysql.jdbc.StringUtils;
import com.utils.dateUtil.DateUtil;
import com.utils.page.PageBean;
import com.utils.security.EncryptionHelper;
import com.utils.security.UUIDGenerator;
import com.wf.course.dao.ICoinLogMapper;
import com.wf.course.dao.IGiveCoinLogMapper;
import com.wf.course.dao.IGoodsOrderMapper;
import com.wf.course.dao.IGoodsOrderRelationMapper;
import com.wf.course.dao.IMemberCouponsMapper;
import com.wf.course.dao.IMemberGoldLogMapper;
import com.wf.course.dao.IMemberMapper;
import com.wf.course.model.goods.GoodsOrder;
import com.wf.course.model.goods.GoodsOrderRelation;
import com.wf.course.model.member.CoinLog;
import com.wf.course.model.member.GiveCoinLog;
import com.wf.course.model.member.Member;
import com.wf.course.model.member.MemberGoldLog;
import com.wf.course.model.ad.MemberCoupons;
import com.wf.course.service.IGoodsOrderService;

@Service
@Transactional(rollbackFor=Exception.class)
public class IGoodsOrderServiceImpl implements IGoodsOrderService{
	
	@Autowired
	private IGoodsOrderMapper mapper;
	@Autowired
	private IMemberMapper memberMapper;
	@Autowired
	private IGoodsOrderRelationMapper relationMapper;
	@Autowired
	private ICoinLogMapper coinLogMapper;
	@Autowired
	private IMemberCouponsMapper imMapper;
	@Autowired
	private IGiveCoinLogMapper giveCoinlog;
	@Autowired
	private IMemberGoldLogMapper imGold;

	@SuppressWarnings("unused")
	@Override
	public void indexInfo(PageBean<GoodsOrder> pageBean) {
		
		List<GoodsOrder>  list = this.mapper.queryList(pageBean);
		String orderCode ="";
		// TODO Auto-generated method stub
		if(pageBean.getConMap()!=null && pageBean.getConMap().size()>0){
			if(pageBean.getConMap().get("orderCode")!=null && !"".equals(pageBean.getConMap().get("orderCode"))){
				orderCode = pageBean.getConMap().get("orderCode").toString();
			}
		} 
		for(GoodsOrder gors : list){
			 orderCode = gors.getOrderCode();
			 String version=gors.getVersion();
			List<GoodsOrder> listName=this.mapper.getGoodsName(orderCode);
			String goodsNames = "";
			
			if(listName!=null &&listName.size()>0){
				
				for(int i = 0;i < listName.size(); i++){
					if (listName.get(i) != null) {
						goodsNames+=listName.get(i).getGoodsNames() +"\n";
				      }
				}
			}
			gors.setGoodsNames(goodsNames);
			
			String realpays="";
			String realpay="0.00";
			realpays=gors.getRealPay();
			if(realpays!=null){
			if(realpays.indexOf('-')!=-1){
				
				gors.setRealPay(realpay);
			}else{
				gors.setRealPay(realpays);
			}
			}else{
				gors.setRealPay(realpay);	
			}
			
			if(version == null ||"".equals(version)){
				gors.setOldCopperCash(gors.getSpendCoin());	
			}else if(version.equals("2.0")){
				gors.setOldCopperCash(gors.getSpendCoin());	
				
			}else if(version.equals("3.0")){
				
				gors.setOldCopperCash(gors.getOldCopperCash());		
			}
			
			//添加标识字段
			String orderPayTime=gors.getOrderPayTime();
			String orderPagTimes="2017-09-29 00:00:00";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				if(orderPayTime!=null){
				if(sdf.parse(orderPayTime).getTime()>sdf.parse(orderPagTimes).getTime()){
					String identification="新订单";
					gors.setIdentification(identification);
				}else{
					String identification="旧订单";
					gors.setIdentification(identification);
					
					
				}
			}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		pageBean.setResults(list);
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean).intValue());
		
	}

	@Override
	public void saveGoodsOrderOrUpdate(GoodsOrder goodsOrder) {
		// TODO Auto-generated method stub
		if(goodsOrder.getId()==null){
			this.mapper.saveGoodsOrder(goodsOrder);
		}else{
			this.mapper.updateGoodsOrderById(goodsOrder);
		}
		
	}

	@Override
	public GoodsOrder queryGoodsOrderById(Integer id) {
		// TODO Auto-generated method stub
		return this.mapper.queryGoodsOrderById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(id);
	}

	@Override
	public GoodsOrder queryGoodsOrderByOrderCode(String  orderCode){
		
		return this.mapper.queryGoodsOrderByOrderCode(orderCode);
	}
	
	@Override
	public List<GoodsOrder> goodOrders(PageBean<GoodsOrder> pageBean){
		return this.mapper.orderList(pageBean);
	}
	
	/**
	 * 删除
	 * @param orderCode
	 */
	@Override
	public void deleteByOrderCode(String  orderCode){
		this.mapper.deleteByOrderCode(orderCode);
	}
	
	@Override
	public void getConfigOrders(PageBean<GoodsOrder> pageBean){
		pageBean.setResults(this.mapper.queryConfigOrdersList(pageBean));
		pageBean.setTotalCount(this.mapper.getConfigOrdersTotal(pageBean).intValue());
	}
	/**
	 * 配置订单
	 * 1.校验手机号是否存在，如果不存在，需要添加用户
	 * 2.根据用户id,添加订单
	 * 3.添加订单-商品（年卡课程章节）关系
	 * 4.判断是否添加铜钱，否：不添加；是：添加
	 */
	@Override
	public void  configGoodsOrder(GoodsOrder goodsOrder,GoodsOrderRelation goodsOrderRelation,GiveCoinLog coinLog){
		
		String time = DateUtil.getDateString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		
		if(goodsOrder!=null){
			//查询手机号是否存在
			List<Member> mbs = memberMapper.queryMembersByTelephone(goodsOrder.getTelephone());
			
			if(mbs==null || mbs.size()==0){
				Member member = new Member();
				String salt = UUIDGenerator.getUUID(false);//随机字符串
				member.setUserUuidSalt(salt);
				String password = EncryptionHelper.encrypt(member.getUserPassword(), salt);//密码
				member.setUserPassword(password);	
				member.setCreateTime(time);//时间
				member.setTelephone(goodsOrder.getTelephone());
				member.setStatus(1);
				member.setBlackFlag(0);
				member.setUserName("wf_"+goodsOrder.getTelephone().substring(5));
				this.memberMapper.saveMember(member);
			} 
			//查找手机号对应的userId
			List<Member> mList = memberMapper.queryMembersByTelephone(goodsOrder.getTelephone());
			 Integer userId = mList.get(0).getUserId();
			 Integer orderStatus= goodsOrder.getOrderStatus();
			 //订单设置用户id
			goodsOrder.setUserId(userId);
			goodsOrder.setOrderTime(time);
			
			//查询当天订单数量
			GoodsOrder dayCount = mapper.getDayCount(DateUtil.getDateString(new SimpleDateFormat("yyMMdd")));
			String sl ="";
			if(dayCount!=null){
				 sl = String.valueOf(dayCount.getDayCount()+1);
			}else{
				 sl = "1";
			}
			
			
			//生成订单号：yyMMddHHmmss+当天订单数量+3位随机数
			String orderCode = DateUtil.getDateString(new SimpleDateFormat("yyMMddHHmmss"))
								+sl+UUIDGenerator.getRandom();
			
			goodsOrder.setOrderCode(orderCode);
			goodsOrder.setOrderAmount("0.00");
			goodsOrder.setGoodsAmount("0.00");
			//保存订单
			this.mapper.saveGoodsOrder(goodsOrder);
			
			//保存订单商品关系表信息1.课程 2.章节3.vip卡4商品
			//订单
			//支持多选课程 start
			
			//商品编号数组
			List<String> goodsIdList = null;	
 			if(goodsOrderRelation.getGoodsSort()==1 && goodsOrderRelation.getCourseIds()!=null){
 				String courseIds = goodsOrderRelation.getCourseIds();
 				if (!StringUtils.isNullOrEmpty(courseIds)) {
					String[] arrcourseIds = courseIds.split(",");
					goodsIdList = Arrays.asList(arrcourseIds);
				}
 				//goodsOrderRelation.setGoodsId(goodsOrderRelation.getCourseId());
			}else if(goodsOrderRelation.getGoodsSort()==2 && goodsOrderRelation.getChapterIds()!=null){
				String chapterIds = goodsOrderRelation.getChapterIds();
				if (!StringUtils.isNullOrEmpty(chapterIds)) {
					String[] arrchapterIds = chapterIds.split(",");
					goodsIdList = Arrays.asList(arrchapterIds);
				}
				//goodsOrderRelation.setGoodsId(goodsOrderRelation.getChapterId());
			}else if(goodsOrderRelation.getGoodsSort()==3 && goodsOrderRelation.getCardIds()!=null){
				String cardIds = goodsOrderRelation.getCardIds();
				if (!StringUtils.isNullOrEmpty(cardIds)) {
					String[] arrcardIds = cardIds.split(",");
					goodsIdList = Arrays.asList(arrcardIds);
				}
				//goodsOrderRelation.setGoodsId(goodsOrderRelation.getCardId());
			} 
 			goodsOrderRelation.setOrderCode(orderCode);//订单编号
			goodsOrderRelation.setGoodsCount(1);
			goodsOrderRelation.setSaleFlag(0);//是否秒杀：默认0：否
			goodsOrderRelation.setGoodsPrice(new BigDecimal(0.0));
 			goodsOrderRelation.setIsEvaluate(2);//是否评价，默认2：否
 			goodsOrderRelation.setBackFlag(0);
 			
 			List<GoodsOrderRelation> list = new ArrayList<>();
 			if (goodsIdList != null && goodsIdList.size()>0) {
 				for (int i = 0; i < goodsIdList.size(); i++) {
 					GoodsOrderRelation gOrderRelation =  new GoodsOrderRelation();
 					gOrderRelation.setGoodsId(Integer.valueOf(goodsIdList.get(i)));
 					gOrderRelation.setOrderCode(orderCode);//订单编号
 					gOrderRelation.setGoodsCount(1);
 					gOrderRelation.setSaleFlag(0);//是否秒杀：默认0：否
 					gOrderRelation.setGoodsPrice(new BigDecimal(0.0));
 					gOrderRelation.setGoodsSort(goodsOrderRelation.getGoodsSort());
 					gOrderRelation.setSpecification("");
 					gOrderRelation.setIsEvaluate(2);//是否评价，默认2：否
 					gOrderRelation.setBackFlag(0);
 					gOrderRelation.setUserId(userId);
 					gOrderRelation.setCreateTime(time);
 					gOrderRelation.setOrderStatus(orderStatus);
 	 	 			list.add(gOrderRelation);
 				}
			}
 			relationMapper.saveBatchGoodsOrderRelation(list);
 			//支持多选课程  end
 			   if(coinLog.getCoinValue().length()>0){
 				   
 				  coinLog.setCoinValue(coinLog.getCoinValue());  
 				   
 			   }else{
 				   
 				  coinLog.setCoinValue("0");
 			   }
 			    //添加新铜钱
 				coinLog.setUserId(userId);
 				coinLog.setOrderCode(orderCode);//订单编号
 				coinLog.setStatus(2);//状态：1.审核 2.成功
 			    coinLog.setType(1);
 				coinLog.setRemarkInfo("【本记录来源于人工配置订单】");
 				giveCoinlog.saveCoinLog(coinLog);
		}
		
	}
	/**
	 * 订单实际支付总金额统计
	 */
	public GoodsOrder goodsTotalAmount(String userSource,String  orderBeginTime,String  orderEndTime){
		
	 return  this.mapper.getTotalAmount(userSource,orderBeginTime,orderEndTime);
	}
	/**
	 * 关闭30分钟内未支付的订单：
	 * 1.查询30分钟内待付款状态的订单：当前时间-订单生成时间>=30，状态是待付款的订单
	 * 2.修改状态为：已取消
	 */
	public void closeGoodsOrders(){
		List<GoodsOrder>  goodsOrders = this.mapper.queryNoPayOrdersList();
		List<String> orderCodes = new ArrayList<String>();
		if(goodsOrders!=null && goodsOrders.size()>0){
			for(int i=0;i<goodsOrders.size();i++){
				String orderCode = goodsOrders.get(i).getOrderCode();
				orderCodes.add(orderCode);
			}
			this.mapper.updateOrderStatus(orderCodes);
		}
		
	}
	
	
	/**
	 * 导出配置订单列表，
	 */
	public List<GoodsOrder> exportConfigGoodsOrder(PageBean<GoodsOrder> pageBean){
		return this.mapper.exportConfigGoodsOrder(pageBean);
	}

	/**
	 * 订单退货
	 * 规则：返回-1退货失败 返回1 退货成功
	 */
	@Override
	public Integer goodsReturn(String orderCode) {
		// TODO Auto-generated method stub
		boolean result = false;
		//1.0   订单表（wf_goods_order）中OrderStatus字段更新为6，退货时间backTime更新为当前时间
		//根据订单编号，获取订单详情
		GoodsOrder goodsOrder = mapper.queryGoodsOrderByOrderCode(orderCode);
		if (goodsOrder!=null) {
			goodsOrder.setOrderStatus(6);
			goodsOrder.setBackTime(DateUtil.getCurrentTime());
			mapper.updateGoodsOrderById(goodsOrder);
			result = true;
		}else{
			return -1;
		} 
		//2.0  订单关系表（wf_goods_order_relation）中该订单编号下所有的对应商品backFlag更改为1
		List<GoodsOrderRelation> goodsOrderRelationsList = relationMapper.queryOrderGoodsList(orderCode);
		if (goodsOrderRelationsList.size() > 0) {
			relationMapper.updateGoodsOrderRelationByorderCode(orderCode,1);
			result = true;
		}else {
			return -1;
		}	
		if (goodsOrderRelationsList.size() > 0) {
			relationMapper.updateGoodsOrderRelationByorderStatus(orderCode,6);
			result = true;
		}else {
			return -1;
		}
		//3.0  是否使用优惠券,是--优惠券返还，用户优惠券表（wf_member_coupons）coupons_source更新为4
		Integer coupons_id = goodsOrder.getCoupons_id();
		if (coupons_id!=null && coupons_id > 0) {
			//获取用户优惠券信息
			MemberCoupons memberCoupons = imMapper.getMemberCoupons(coupons_id);
			memberCoupons.setCoupons_source(4);
			memberCoupons.setStatus(2);
			imMapper.updateMemberCoupons(memberCoupons);
			result = true;
		}
		
		//4.0 是否使用铜钱,是--铜钱返还，用户存钱罐信息记录表（wf_coin_log）中根据订单编号，把该订单编号下所有的deleteFlag更新为1（已删除状态）
		String copperCash = goodsOrder.getOldCopperCash();
		String copperCashs=goodsOrder.getCopperCash();
		if(copperCash.equals("0.00")){
			copperCash=null;
			
		}
		if (!StringUtils.isNullOrEmpty(copperCash)) {
			int deleteFlag=1;
			coinLogMapper.updateCoinLogByOrderCode(orderCode,deleteFlag);
			result = false;
		}
		 if(!StringUtils.isNullOrEmpty(copperCashs)){
			 int deleteFlag=1;
				coinLogMapper.updateCoinLogByOrderCode(orderCode,deleteFlag);
				result = false; 
		 }
		
		//5.0 是否使用新铜钱,是--新铜钱返还，用户存钱罐信息记录表（wf_member_give_coin_log）中根据订单编号，把该订单编号下所有的type更新为3（已删除状态）
		String newcopperCash = goodsOrder.getNewCopperCash();

		if(newcopperCash != null && newcopperCash.equals("0.00")){
			newcopperCash=null;
			
		}
		   
		if (!StringUtils.isNullOrEmpty(newcopperCash)) {
			GiveCoinLog givecoinlog = giveCoinlog.getorderCode(orderCode);
			Integer touserid=givecoinlog.getToUserId();
		
				if(touserid !=null){
					givecoinlog.setToUserId(touserid);
				}else{
					givecoinlog.setToUserId(0);
				}
			
			givecoinlog.setType(3);
			givecoinlog.setStatus(2);
			givecoinlog.setRemarkInfo("退还新铜钱支付");
			giveCoinlog.savememberGivecoin(givecoinlog);
			result = false;
		}
		 
		
		//6.0 是否使用金币,是--金币返还，用户存钱罐信息记录表（wf_member_gold_log）中根据订单编号，把该订单编号下所有的type更新为3（已删除状态）
				String gold = goodsOrder.getGold();
				if(gold != null && gold.equals("0.00")){
					gold=null;
					
				}
				if (!StringUtils.isNullOrEmpty(gold)) {
					MemberGoldLog membergoldlog = imGold.getMemberorderCode(orderCode);
					membergoldlog.setType(3);
					membergoldlog.setStatus(2);
					membergoldlog.setRemarkInfo("退还金币支付");
					imGold.savememberGold(membergoldlog);
					result = false;
				}

		// 新金币退换
		String newGold = goodsOrder.getNewGold();
		if (newGold != null && newGold.equals("0.00")) {
			newGold = null;
		}
		if (!StringUtils.isNullOrEmpty(newGold)) {
			MemberGoldLog newMembergoldlog = imGold.getMemberNewGoldByOrderCode(orderCode);
			newMembergoldlog.setType(3);
			newMembergoldlog.setStatus(2);
			newMembergoldlog.setRemarkInfo("退还金币支付");
			imGold.saveMemberNewGold(newMembergoldlog);
			result = false;
		}
				 
				return result ? 1 :-1;
	}

	@Override
	public GoodsOrder queryGoodsOrderByOrderCodes(String orderCode) {
		return this.mapper.queryGoodsOrderByOrderCodes(orderCode);
	}

	@Override
	public List<GoodsOrder> getGoodsNames(String orderCode) {
		List<GoodsOrder> list = this.mapper.getGoodsName(orderCode);
		return list;
	}

	@Override
	public void goodsupdateOrderRemark(String orderCode, String uqdateremark) {
		    GoodsOrder goodsOrder = mapper.queryorderCode(orderCode);
		    goodsOrder.setOrderRemark(uqdateremark);
			mapper.updateGoodsOrderById(goodsOrder);
		
		
	}
}
